<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!DOCTYPE html>
<html>
    <head>
        <title>chat application</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="style.css">
        <script type="text/javascript" src="jquery-1.8.3.js"></script>
        
        <script>
            // post a new message
            var postMessage = function() {
                var data = $("#message").val();
                $.post(
                        "post", 
                        data,
                        function() {
                            displayPost("me",data,true);
                        }
                );
            }

            // display a post
            var displayPost = function(user,text,thisUser) {
                var clazz = thisUser?"thisuser":"otheruser";
                var tr = '<tr class="' + clazz + '"><td class="message_user">'+ user + '</td><td class="message_text">' + text + '</td></tr>'
                document.getElementById("conversation").innerHTML+=tr;
            }
            
            // listen to server push
            var source = new EventSource("fetch");
            source.onmessage = function(event) {
                if (event.data) { // only update if the string is not empty
                    console.log("data received: " + event.data);
                    var messages = jQuery.parseJSON(event.data);
                    for (var i in messages) {
                        displayPost(messages[i].user,messages[i].text,false);
                    }
                }
            };
        </script>
        
    </head>
    <body>
            <h3>A Simple Web Messaging Application using Server-Sent Events</h3>
            <table>
                <tr>
                    <td>user name:</td>
                    <td><%= session.getAttribute("_user") %></td>
                </tr>
                <tr>
                    <td>conversation:</td>
                    <td> <%= session.getAttribute("_conversation") %></td>
                </tr>
            </table>
            
            <p/>
            type here: <input id="message" type="text" size="60" onkeydown="if (event.keyCode == 13) postMessage()"/>
            <button onclick="postMessage()">send</button>
            
            <hr/>
            
            <table class="conversation">
                <tbody id="conversation" class="conversation"></tbody>
            </table>
            
            <hr/>
            <a href="leave">leave conversation</a>
            
    </body>
</html>
